package com.itcast.donkey.activity;

import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.TranslateContentAdapter;
import com.itcast.donkey.application.MyApplication;
import com.itcast.donkey.modles.TranslateModles;
import com.itcast.donkey.popwindow.PopEndLangueList;
import com.itcast.donkey.popwindow.PopLangueList;

import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.x;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/9/6.
 */
public class ToolTranslateActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout linScenicSpot;
    private ImageView backScenicApot;
    private ImageView ivChanScenicSpot;
    private TextView tvTitleScenicSpot;
    private TextView tvFrontTranslate;
    private ImageView ivExchange;
    private TextView tvEndTranslate;
    private ImageView ivBeginTape;
    private ImageView ivTranslate;

    private TextView tv;
    //显示内容的RecyclerView
    private RecyclerView recyclerView;

    private EditText editText;

    private PopLangueList popLangueList;
    private PopEndLangueList endPopLangueList;

    private String[] front = {"自动检测", "中文", "粤语", "英语", "日语", "韩语", "西班牙语", "法语", "泰语", "阿拉伯语", "俄罗斯语"
            , "葡萄牙语", "德语", "意大利语"};
    private String end[] = {"中文", "粤语", "英语", "日语", "韩语", "西班牙语", "法语", "泰语", "阿拉伯语", "俄罗斯语"
            , "葡萄牙语", "德语", "意大利语"};

    private SpeechSynthesizer mySynthesizer;
    private RecognizerDialog dialog;
    private SharedPreferences sharedPreferences;
    private SpeechRecognizer mIat;

    private String result;

    //适配器
    private TranslateContentAdapter adapter;
    //布局管理器
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tool_translate);
        SpeechUtility.createUtility(ToolTranslateActivity.this, SpeechConstant.APPID + "=57cea70c");

        initView();
        initData();
        initEvent();
        //1.创建SpeechSynthesizer对象，第二个参数：本地听写时传InitListener
        mySynthesizer = SpeechSynthesizer.createSynthesizer(this, myInitListener);


        mIat = SpeechRecognizer.createRecognizer(this, myInitListener);
    }

    private InitListener myInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("mySynthesiezer:", "InitListener init() code = " + code);
        }
    };

    private void initView() {
        linScenicSpot = (LinearLayout) findViewById(R.id.lin_scenic_spot);
        backScenicApot = (ImageView) findViewById(R.id.back_scenic_apot);
        ivChanScenicSpot = (ImageView) findViewById(R.id.iv_chan_scenic_spot);
        tvTitleScenicSpot = (TextView) findViewById(R.id.tv_title_scenic_spot);
        tvFrontTranslate = (TextView) findViewById(R.id.tv_front_translate);
        ivExchange = (ImageView) findViewById(R.id.iv_exchange);
        tvEndTranslate = (TextView) findViewById(R.id.tv_end_translate);
        ivBeginTape = (ImageView) findViewById(R.id.iv_begin_tape);
        ivTranslate = (ImageView) findViewById(R.id.iv_translate);
        editText = (EditText) findViewById(R.id.et_translate);

        recyclerView = (RecyclerView) findViewById(R.id.listview_tool_translate);
        //设置布局管理器
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);


        popLangueList = new PopLangueList(ToolTranslateActivity.this, onItemClickListener, front);
        endPopLangueList = new PopEndLangueList(ToolTranslateActivity.this, endOnItemClickListener, end);
    }


    private ListView.OnItemClickListener endOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            tvEndTranslate.setText(end[position]);
        }
    };
    private ListView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            tvFrontTranslate.setText(front[position]);
        }
    };


    private void initData() {

        //显示数据库
        sqlShow();
    }

    private void initEvent() {
        backScenicApot.setOnClickListener(this);
        ivChanScenicSpot.setOnClickListener(this);
        tvFrontTranslate.setOnClickListener(this);
        ivExchange.setOnClickListener(this);
        tvEndTranslate.setOnClickListener(this);
        ivBeginTape.setOnClickListener(this);
        ivTranslate.setOnClickListener(this);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (editText.getText().toString().length() != 0) {
                    //翻译按钮是否可点击
                    ivTranslate.setBackgroundResource(R.mipmap.translation_normal);
                    ivTranslate.setEnabled(true);
                } else {
                    ivTranslate.setBackgroundResource(R.mipmap.translation_disable);
                    ivTranslate.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //显示数据库里边的内容
    public void sqlShow() {
        MyApplication application = new MyApplication();
        DbManager db = x.getDb(application.getConfig());

        try {
            List<TranslateModles> modlesList = db.selector(TranslateModles.class).findAll();
            if (modlesList.size() > 0) {
                adapter = new TranslateContentAdapter(ToolTranslateActivity.this, modlesList);
                recyclerView.setAdapter(adapter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(ToolTranslateActivity.this, "获取网络失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:


                    //将文本框清空
                    editText.setText(null);
                    //去掉翻译后前后的括号
                    String a = result.substring(2, result.length() - 2);
                    //文字翻译
                    //设置发音人
                    mySynthesizer.setParameter(SpeechConstant.VOICE_NAME, "lingxi");
                    //设置音调
                    mySynthesizer.setParameter(SpeechConstant.PITCH, "50");
                    //设置音量
                    mySynthesizer.setParameter(SpeechConstant.VOLUME, "200");
                    int code = mySynthesizer.startSpeaking(a, mTtsListener);

                    //显示数据库里边的内容
                    sqlShow();
                    break;
                case 2:
                    Toast.makeText(ToolTranslateActivity.this, "没内容", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //返回按钮
            case R.id.back_scenic_apot:
            case R.id.iv_chan_scenic_spot:
                finish();
                break;
            case R.id.tv_front_translate:
                //左边的下拉
                popLangueList.showAsDropDown(tvFrontTranslate);
                break;
            case R.id.iv_exchange:
                //交换
                if (!tvFrontTranslate.getText().toString().equals(front[0])) {
                    String name = tvFrontTranslate.getText().toString();
                    tvFrontTranslate.setText(tvEndTranslate.getText().toString());
                    tvEndTranslate.setText(name);
                }
                break;
            case R.id.tv_end_translate:
                //右边的下拉
                endPopLangueList.showAsDropDown(tvEndTranslate, 0, 0, Gravity.RIGHT);
                break;
            case R.id.iv_begin_tape:
                //语音听写

                mIat.setParameter(SpeechConstant.DOMAIN, "iat");
                mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
                mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
                //3.开始听写
                mIat.startListening(mRecognizerListener);
                //Dialog
                RecognizerDialog iatDialog = new RecognizerDialog(ToolTranslateActivity.this, myInitListener);
                iatDialog.setListener(recognizerDialogListener);
                iatDialog.show();
                break;
            case R.id.iv_translate:

                //点击进入翻译，并且把内容放入数据库
                translate();
                break;
        }
    }


    //开始翻译的方法
    private void translate() {
        if (!"".equals(editText.getText().toString().trim())) {
            final String url = "http://fanyi.youdao.com/openapi.do?keyfrom=2a2abcsdas&" +
                    "key=429839198&type=data&doctype=json&version=1.1&q="
                    + editText.getText().toString();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpClient client = new OkHttpClient();
                    final Request request = new Request.Builder()
                            .url(url)
                            .build();

                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            handler.sendEmptyMessage(0);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String name = response.body().string();

                            try {
                                JSONObject jsonObject = new JSONObject(name);
                                result = jsonObject.getString("translation");
                                MyApplication application = new MyApplication();
                                DbManager db = x.getDb(application.getConfig());

                                TranslateModles modles = new TranslateModles();
                                modles.setTranslateFront(editText.getText().toString().trim());
                                String a = result.substring(2, result.length() - 2);
                                modles.setTranslateEnd(a);
                                db.save(modles);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (!"".equals(result)) {
                                handler.sendEmptyMessage(1);
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                        }
                    });
                }
            }).start();
        }
    }

    private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {

        @Override
        public void onResult(RecognizerResult arg0, boolean arg1) {
            String text = com.itcast.donkey.popwindow.JsonParser.parseIatResult(arg0.getResultString());
            editText.append(text);
            editText.setSelection(editText.length());
        }

        @Override
        public void onError(SpeechError arg0) {

        }
    };


    //语音监听事件
    private SynthesizerListener mTtsListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {

        }

        @Override
        public void onSpeakPaused() {

        }

        @Override
        public void onSpeakResumed() {

        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        @Override
        public void onCompleted(SpeechError error) {
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    //语音听写的监听事件
    private RecognizerListener mRecognizerListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {

        }

        @Override
        public void onBeginOfSpeech() {

        }

        @Override
        public void onEndOfSpeech() {

        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {


        }

        @Override
        public void onError(SpeechError speechError) {
            Log.i("result", "onError");
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {
            Log.i("result", "onEvent");
        }
    };
}
